package com.itheima.mp.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.dto.UserFormDTO;
import com.itheima.mp.domain.po.Address;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.AddressVO;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 张文接
 * @version 1.0
 * @createTime 2024/6/15 20:05
 */
@Api(tags = "用户管理")
@RestController
@RequestMapping("/users")
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping
    @ApiOperation("新增用户")
    public void saveUser(@RequestBody UserFormDTO userFormDTO) {
        User user = BeanUtil.copyProperties(userFormDTO, User.class);
        userService.save(user);
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除用户")
    public void deleteUser(@PathVariable Long id) {
        userService.removeById(id);
    }

    @GetMapping("/{id}")
    @ApiOperation("根据id查询用户")
    public UserVO findById(@PathVariable Long id) {
        User user = Db.getById(id, User.class);
        List<Address> addresses = Db.lambdaQuery(Address.class).eq(Address::getUserId, user.getId()).list();
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        List<AddressVO> addressVOS = BeanUtil.copyToList(addresses, AddressVO.class);
        userVO.setAddresses(addressVOS);
        return userVO;
    }

    @GetMapping
    @ApiOperation("根据id集合查询用户")
    public List<UserVO> findByIds(@RequestParam("ids") List<Long> ids) {
        List<User> users = userService.listByIds(ids);
        return BeanUtil.copyToList(users, UserVO.class);
    }

    @ApiOperation("扣减用户余额")
    @PutMapping("/{id}/deduct/{money}")
    public void deductBalance(@PathVariable("id") Long id, @PathVariable("money") Integer money) {
        userService.deductBalance(id, money);
    }

    @GetMapping("/list")
    @ApiOperation("条件查询")
    public List<UserVO> queryUser(UserQuery query) {
        List<User> users = userService.queryUser(query.getName(), query.getStatus(), query.getMaxBalance(), query.getMinBalance());
        return BeanUtil.copyToList(users, UserVO.class);
    }

    @GetMapping("/page")
    @ApiOperation("条件分页查询")
    public PageDTO<UserVO> queryUsersPage(UserQuery userQuery) {
        return userService.queryUsersPage(userQuery);
    }
}
